package com.ankicoo.auth.filter;

import com.ankicoo.common.response.ResponseBody;
import com.ankicoo.common.response.ResponseCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * Description: 判断请求是否已经成功进行身份认证
 *
 * @author : QCYANG
 * @date : 2021/1/11 9:57
 */
public class LoginFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o){
        Subject subject = SecurityUtils.getSubject();
        if (subject != null && subject.isAuthenticated()) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 连接被拒绝时判断是否是登录请求
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (!isLoginRequest(request, response)) {
            PrintWriter out;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            out.write(mapper.writeValueAsString(ResponseBody.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
                    ResponseCode.NEED_LOGIN.getDesc() + "(其它环境删掉:补充说明，如果前端页面渲染触发访问后端需要登录权限的接口，最好在前端做判断限制)")));
            return false;
        }
        return true;
    }
}
